package com.buddy.learn.network.netty.demo03.server;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;

import java.nio.charset.StandardCharsets;

/**
 * @author WongZP
 * @date 2022/4/21
 */
public class MyNettyServerInboundHandler extends ChannelInboundHandlerAdapter {
    int count = 0;

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.println("server read handler");
        ByteBuf byteBuf = (ByteBuf) msg;
        System.out.println("client msg:" + byteBuf.toString(CharsetUtil.UTF_8));
        System.out.println("读取次数:" + (++count));
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        System.out.println("server read complete...");
        ChannelFuture future = ctx.writeAndFlush(Unpooled.copiedBuffer("hi clinet,i'm server...".getBytes(StandardCharsets.UTF_8)));
        future.addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                System.out.println("server send complete");
            }
        });
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}
